<template>
  <div>
    <el-card class="box-card" style="margin:20px">
      <div slot="header" class="clearfix">
        <el-form :inline="true">
          <el-form-item v-if="routeData.itemId != null" style="margin-bottom:0px;">
            <el-button icon="el-icon-back" @click="back">返回</el-button>
          </el-form-item>
          <el-form-item label="名称" style="margin-bottom:0px;">
            <el-input v-model="searchName" placeholder="输入名称" />
          </el-form-item>
          <el-form-item label="所属系统" style="margin-bottom:0px;">
            <el-select
              v-model="serchForm.systemId"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                v-for="item in systemOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-bottom:0px;">
            <el-select
              v-model="serchForm.status"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                label="未发布"
                :value="0"
              />
              <el-option
                label="已发布"
                :value="1"
              />
              <el-option
                label="有新版本"
                :value="2"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态" style="margin-bottom:0px;">
            <el-select
              v-model="serchForm.active"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                label="停用"
                :value="0"
              />
              <el-option
                label="启用"
                :value="1"
              />
            </el-select>
          </el-form-item>
          <el-form-item style="margin-bottom:0px;">
            <el-button type="primary" icon="el-icon-search" @click="getFlowList">查询</el-button>
            <el-button type="primary" icon="el-icon-edit" @click="add">新增</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table v-loading="loading" :data="tableData" :row-class-name="tableRowClassName" style="width: 100%">
        <el-table-column
          fixed="left"
          prop="name"
          label="名称"
          width="300"
        />
        <el-table-column
          width="200"
          prop="flowKey"
          label="模型ID"
        />
        <el-table-column
          width="200"
          prop="systemName"
          label="所属系统"
        />
        <el-table-column
          width="200"
          prop="systemId"
          label="租户id"
        />
        <el-table-column
          prop="status"
          label="发布状态"
          :formatter="formatStatus"
          width="70"
        />
        <el-table-column
          prop="active"
          label="状态"
          :formatter="formatActive"
          width="50"
        />
        <!-- <el-table-column
          fixed
          prop="version"
          label="版本号"
          min-width="10%"
        /> -->
        <el-table-column
          width="300"
          prop="processKey"
          label="processKey"
        />
        <el-table-column
          width="200"
          prop="updateTime"
          label="更新时间"
        />
        <el-table-column
          fixed="right"
          align="center"
          label="操作"
          width="400"
        >
          <template slot-scope="scope">
            <el-button
              v-if="routeData.itemId != null"
              size="mini"
              type="success"
              icon="el-icon-paperclip"
              @click="bind(scope.$index, scope.row)"
            >
              绑定
            </el-button>
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-edit"
              @click="update(scope.$index, scope.row)"
            >
              编辑
            </el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="remove(scope.$index, scope.row)"
            >
              删除
            </el-button>
            <el-button
              v-loading="loading"
              size="mini"
              type="primary"
              icon="el-icon-document"
              @click="edit(scope.$index, scope.row)"
            >
              流程图
            </el-button>
            <el-button
              v-loading="loading"
              size="mini"
              type="primary"
              icon="el-icon-document"
              @click="publish(scope.$index, scope.row)"
            >
              发布
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block" style="float:right;margin:20px">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      <div>
        <el-dialog title="流程信息" :visible.sync="dialogFlowVisible">
          <el-form ref="flowForm" label-width="100px" size="mini" :model="flowForm" :rules="rules">
            <el-form-item label="流程名称" prop="name">
              <el-input
                v-model="flowForm.name"
              />
            </el-form-item>
            <el-form-item label="所属系统" prop="systemId">
              <el-select
                v-model="flowForm.systemId"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in systemOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="active">
              <el-radio-group v-model="flowForm.active">
                <el-radio :label="0">停用</el-radio>
                <el-radio :label="1">启用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFlowVisible = false">取 消</el-button>
            <el-button type="primary" @click="addOrUpdate">确 定</el-button>
          </div>
        </el-dialog>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      fullscreen: true,
      routeData: this.$route.params,
      tableData: [{}],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogFlowVisible: false,
      flowForm: {
        name: '',
        active: 0,
        status: 0,
        systemId: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入流程名称', trigger: 'blur' }
        ],
        systemId: [
          { required: true, message: '请选择业务系统', trigger: 'change' }
        ]
      },
      updateFlowId: 0,
      systemOptions: [],
      searchName: '',
      designUrl: null,
      dialogVisible: false,
      newProcessDiagramXml: '',
      processInfo: {},
      loading: false,
      processDetailId: 1,
      serchForm: {
        active: '',
        status: '',
        systemId: ''
      }
    }
  },
  mounted() {
    this.getFlowList()
    this.getSystemOptions()
  },
  methods: {
    // 发布
    publish(index, row) {
      this.$axios.post(this.baseFlowUrl + '/deploy/model/' + row.flowKey + '/' + row.name)
        .then(res => {
          if (res && res.data && res.data.code === 200) {
            this.$message.success('发布成功')
            this.getFlowList()
          } else {
            this.$message.error((res.data && res.data.msg) ? res.data.msg : '发布失败')
          }
        }).catch((e) => { console.error(e) })
    },
    getFlowList() {
      this.loading = true
      var params = {
        'pageSize': this.pageSize,
        'pageNum': this.currentPage,
        'name': this.searchName,
        'systemId': this.serchForm.systemId,
        'status': this.serchForm.status,
        'active': this.serchForm.active
      }
      this.$axios.get(this.baseFlowUrl + '/flow/page', {
        params
      }).then(res => {
        this.tableData = res.data.data.records
        this.total = parseInt(res.data.data.total)
        this.loading = false
      }).catch(() => {
        this.loading = false
        this.$message.error('获取流程列表失败')
      })
    },
    edit(index, row) {
      this.loading = true
      if (row.flowKey) {
        const that = this
        this.$axios.get(this.baseFlowUrl + '/model/getById/' + row.flowKey)
          .then(res => {
            if (res.data.code === 200) {
              that.newProcessDiagramXml = res.data.data
              localStorage.setItem('flowTemplate', that.newProcessDiagramXml)
              that.processInfo = { processKey: row.id, processName: row.name, processId: row.flowKey, tenantId: row.systemId, flowUrl: row.flowUrl }
              that.loading = false
              that.$router.push({ name: 'design', params: this.processInfo })
            }
          }).catch((e) => {
            this.loading = false
            console.error(e)
            this.$message.error('获取流程模型数据失败')
          })
      } else {
        this.newProcessDiagramXml = ''
        localStorage.setItem('flowTemplate', this.newProcessDiagramXml)
        this.processInfo = { processKey: row.id, processName: row.name, processId: '', tenantId: row.systemId, flowUrl: row.flowUrl }
        console.log(this.processInfo)
        this.loading = false
        this.$router.push({ name: 'design', params: this.processInfo })
      }
    },
    handleClose() {
      this.dialogVisible = false
      this.getFlowList()
    },
    addOrUpdate() {
      this.$refs['flowForm'].validate((valid) => {
        if (valid) {
          var params = {
            'name': this.flowForm.name,
            'active': this.flowForm.active,
            'systemId': this.flowForm.systemId
          }
          var url = this.baseFlowUrl + '/flow/create'
          if (this.updateFlowId != 0) {//eslint-disable-line
            url = this.baseFlowUrl + '/flow/update'
            this.$set(params, 'id', this.updateFlowId)
          } else {
            this.$set(params, 'version', 1)
            this.$set(params, 'status', 0)
          }
          this.$axios.post(url,
            params
          ).then(res => {
            this.$message.success('操作成功~')
            this.dialogFlowVisible = false
            this.getFlowList()
          }).catch(() => {
            this.$message.error('操作失败！')
          })
        } else {
          this.$message.error('请正确输入')
          return false
        }
      })
    },
    remove(index, row) {
      this.$confirm('此操作将永久删除该模板, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        this.$axios.delete(this.baseFlowUrl + '/flow', {
          params: {
            flowId: row.id
          }
        }).then(res => {
          if (res.data.code === 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.getFlowList()
          } else {
            this.$message({
              type: 'error',
              message: res.data.msg
            })
          }
        }).catch(() => {
          this.$message({
            type: 'error',
            message: '删除失败'
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.getFlowList()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.getFlowList()
    },
    formatStatus(row, column, cellValue, index) {
      if (row.status == 10) {//eslint-disable-line
        return '已发布'
      } else if (row.status === 5) {
        return '有新版本'
      } else {
        return '未发布'
      }
    },
    formatActive(row, column, cellValue, index) {
      if (row.active == 0) {//eslint-disable-line
        return '停用'
      } else {
        return '启用'
      }
    },
    update(index, row) {
      if (this.$refs['flowForm'] !== undefined) {
        this.$refs['flowForm'].resetFields()
      }
      this.$set(this.flowForm, 'name', row.name)
      this.$set(this.flowForm, 'active', row.active)
      this.$set(this.flowForm, 'status', row.status)
      this.$set(this.flowForm, 'systemId', row.systemId)
      this.updateFlowId = row.id
      this.dialogFlowVisible = true
    },
    add() {
      if (this.$refs['flowForm'] !== undefined) {
        this.$refs['flowForm'].resetFields()
      }
      this.$set(this.flowForm, 'name', '')
      this.$set(this.flowForm, 'active', 0)
      this.$set(this.flowForm, 'status', 0)
      this.$set(this.flowForm, 'systemId', '')
      this.updateFlowId = 0
      this.dialogFlowVisible = true
    },
    bind(index, row) {
      var params = {
        'id': this.routeData.itemId,
        'flowId': row.id
      }
      this.$axios.post(this.baseItemUrl + '/item/update',
        params
      ).then(res => {
        this.$message.success(this.routeData.itemName + '与' + row.name + '绑定成功')
        this.routeData.flowId = row.id
        this.getFlowList()
      }).catch(() => {
        this.$message.error('操作失败！')
      })
    },
    back() {
      this.$router.push({ name: 'itemList',
        params: {
          'itemCurrentPage': this.routeData.itemCurrentPage,
          'itemPageSize': this.routeData.itemPageSize
        }
      })
    },
    tableRowClassName({ row, rowIndex }) {
      if (row.id === this.routeData.flowId) {
        return 'success-row'
      }
      return ''
    },
    getSystemOptions() {
      this.$axios.get(this.basePortalUrl + '/system/findAll'
      ).then(res => {
        this.systemOptions = res.data.data
      }).catch(() => {
        this.$message.error('获取业务系统失败')
      })
    }
  }
}
</script>
<style>
  .el-table .success-row {
    background: #f0f9eb;
  }
  .dialogClass .el-dialog__header {
    padding:0px;
  }
  .dialogClass .el-dialog__body {
    padding:0px;
  }
  .designer /deep/ aside {
    padding: 0px;
  }
</style>
